<template>
  <a-card size="small" :bordered="false" title="文件分组">
    <table-toolbar v-model:columns="tableColumns" @reload="handleLoadData">
      <template #left>
        <a-button type="primary" @click="handleAdd(0)">
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </template>
    </table-toolbar>

    <a-table
      :loading="loading"
      :columns="tableColumns"
      :data-source="tableDataSource"
      :pagination="false"
      row-key="groupId"
      size="middle"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button type="primary" size="small" style="margin-right: 5px" @click="handleAdd(record.groupId)">
            <template #icon><PlusOutlined /></template>
            新增
          </a-button>
          <a-button type="primary" size="small" style="margin-right: 5px" @click="handleEdit(record.groupId)">
            <template #icon><FormOutlined /></template>
            编辑
          </a-button>

          <a-popconfirm title="确定删除吗?" ok-text="确定" cancel-text="取消" @confirm="handleDel(record.groupId)">
            <a-button type="primary" danger size="small">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <attach-group-edit ref="editRef" @reload="handleLoadData" />
  </a-card>
</template>

<script name="AttachGroupIndex" lang="ts" setup>
import { delGroup, getTree } from "@/api/content/attachGroup";
import { formatTreeSelect, formatTreeTable } from "@/utils/format";
import AttachGroupEdit from "./edit.vue";

const loading = ref<boolean>(true);
const tableColumns = ref<TableColumn[]>([
  {
    title: "分组名称",
    dataIndex: "groupName",
    key: "groupName"
  },
  {
    title: "排序",
    dataIndex: "sort",
    key: "sort"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime"
  },
  {
    title: "操作",
    dataIndex: "",
    key: "action",
    fixed: "right",
  }
]);
const tableDataSource = ref([]);
const selectDataSource = ref<any>([]);
provide("selectDataSource", selectDataSource);

const handleLoadData = () => {
  loading.value = true;
  getTree()
    .then(response => {
      tableDataSource.value = formatTreeTable(response.data);
      selectDataSource.value = formatTreeSelect(response.data);
    })
    .finally(() => {
      loading.value = false;
    });
};

const editRef = ref();
const handleAdd = (parentId: number) => {
  editRef.value.handleAdd(parentId);
};

const handleEdit = (id: number) => {
  editRef.value.handleEdit(id);
};

const handleDel = (id: number) => {
  loading.value = true;
  delGroup(id)
    .then(() => {
      handleLoadData();
      antdMessage.success("删除成功");
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  handleLoadData();
});
</script>
